outside = r"py_test\text\image\xt1.png"
inside = r"py_test\text\image\xt2.png"
result_path = r"py_test\text\image\result.png"

import cv2
import numpy as np

def load_and_preprocess(image_path):
    """加载图像并转换为灰度图"""
    img = cv2.imread(image_path, 0)
    if img is None:
        raise ValueError(f"无法读取图像: {image_path}")
    return img

def resize_to_match(base_w, base_h, target_w, target_h):
    """计算保持比例的缩放尺寸"""
    scale = max(base_w / target_w, base_h / target_h)
    return (int(target_w * scale), int(target_h * scale))

def process_images(imgA, imgB):
    # 预处理：自动缩放较小图像
    hA, wA = imgA.shape
    hB, wB = imgB.shape
    
    # 判断是否需要缩放
    if wA < wB and hA < hB:
        new_size = resize_to_match(wB, hB, wA, hA)
        imgA = cv2.resize(imgA, new_size, interpolation=cv2.INTER_CUBIC)
    elif wB < wA and hB < hA:
        new_size = resize_to_match(wA, hA, wB, hB)
        imgB = cv2.resize(imgB, new_size, interpolation=cv2.INTER_CUBIC)
    
    return imgA, imgB

def create_canvas(img1, img2):
    """创建统一尺寸的画布"""
    h1, w1 = img1.shape
    h2, w2 = img2.shape
    max_w = max(w1, w2)
    max_h = max(h1, h2)
    return (
        np.zeros((max_h, max_w, 4), dtype=np.uint8),
        np.zeros((max_h, max_w, 4), dtype=np.uint8)
    )

def paste_center(canvas, image):
    """将图像居中放置到画布"""
    h, w = image.shape[:2]
    canvas_h, canvas_w = canvas.shape[:2]
    x = (canvas_w - w) // 2
    y = (canvas_h - h) // 2
    
    # 处理单通道灰度转四通道RGBA
    if len(image.shape) == 2:
        rgba = cv2.cvtColor(image, cv2.COLOR_GRAY2RGBA)
    else:
        rgba = image
    
    canvas[y:y+h, x:x+w] = rgba
    return canvas

# 主程序流程
try:
    # 读取图像
    imgA = load_and_preprocess(outside)
    imgB = load_and_preprocess(inside)
    
    # 自动缩放处理
    imgA, imgB = process_images(imgA, imgB)
    
    # 创建画布
    canvasA, canvasB = create_canvas(imgA, imgB)
    
    # 将图像居中放置到画布
    canvasA = paste_center(canvasA, imgA)
    canvasB = paste_center(canvasB, imgB)
    
    # 调整亮度
    canvasA[..., :3] = np.clip(canvasA[..., :3], 102, 255)  # 提亮
    canvasB[..., :3] = (canvasB[..., :3] * 0.4).astype(np.uint8)  # 压暗
    
    # 计算透明度
    alpha = 255 - (canvasA[..., 0] - canvasB[..., 0])
    alpha = np.clip(alpha, 1, 255)
    
    # 混合图像
    blended = canvasB.copy()
    blended[..., 0] = np.clip(canvasB[..., 0] * 255.0 / alpha, 0, 255).astype(np.uint8)
    blended[..., 1:3] = blended[..., [0,0]]  # 保持灰度
    blended[..., 3] = alpha
    
    # 保存结果
    cv2.imwrite(result_path, blended)

except Exception as e:
    print(f"处理出错: {str(e)}")